home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 319 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.7 KB  |  63 lines

  1. Path: locutus.rchland.ibm.com!usenet
  2. From: pstaite@vnet.ibm.com
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Question about destructor...
  5. Date: 3 Jan 1996 18:48:03 GMT
  6. Organization: IBM OS/2 Device Driver Development  Rochester, MN
  7. Message-ID: <4cej13$usb@locutus.rchland.ibm.com>
  8. References: <4ce9mk$atg@eng_ser1.erg.cuhk.hk>
  9. Reply-To: pstaite@vnet.ibm.com
  10. NNTP-Posting-Host: warpone.rchland.ibm.com
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4ce9mk$atg@eng_ser1.erg.cuhk.hk>, ywleung@cs.cuhk.hk (Marty McFly) writes:
  14. >Dear All,
  15. >
  16. >    I now have 2 classes A and B.  B is a derived class of A.  However,
  17. >the internal implementation of A is not known, i.e., the private members of
  18. >class A are not provided, only the public members are given.  But class B is 
  19. >implemented by myself.  So what should be written in the destructor of B so 
  20. >that all the private members inherited from A are also "deleted"?
  21.  
  22. In a word, nothing.  When you destroy a B object the destructor for the 
  23. A part of it will be called automatically.  Try this little example:
  24.  
  25. #include<iostream.h>
  26.  
  27. class A {
  28.   public:
  29.     A() { cout << "A::A()" << endl; }
  30.     ~A() { cout << "A::~A()" << endl; }
  31. };
  32.  
  33. class B : public A {
  34.   public:
  35.     B() { cout << "B::B()" << endl; }
  36.     ~B() { cout << "B::~B()" << endl; }
  37. };
  38.  
  39. int main() {
  40.     cout << "Making a B object:" << endl;
  41.     B *pb( new B );
  42.     cout << "Destroying a B object" << endl;
  43.     delete pb;
  44.     return 0; }
  45.  
  46. When run this should produce:
  47.  
  48. Making a B object:
  49. A::A()
  50. B::B()
  51. Destroying a B object
  52. B::~B()
  53. A::~A()
  54.  
  55. Note that the A part of the B is constructed first, a destructed last. 
  56. Think of it as the "foundation" for the B -- that is, the B class builds
  57. on top of it.
  58.  
  59.  
  60. Phil Staite, team OS/2
  61. internet: pstaite@vnet.ibm.com  internal: pstaite@rchland
  62.  
  63.